package com.itheima.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @PackageName: com.itheima.utils
 * @ClassName: AliFileUtil
 * @Author: Solomon
 * @Date: 2020/7/2 19:14
 * @Description:
 */
public class AliFileUtil {

    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static final String accessKeyId = "LTAI4GBsW4D1XRQSePqR2DPj";
    private static final String accessKeySecret = "fJERdJ6WW3dhMhqvEvkqUgzr2Rim0K";
    private static final String bucketName = "lijie-health";

    //字节流上传图片
    public static String ByteUpload(MultipartFile imgFile) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String originalFilename = imgFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newImgName = UUID.randomUUID() + substring;

        // 上传Byte数组
        ossClient.putObject(bucketName, newImgName, new ByteArrayInputStream(imgFile.getBytes()));
        // 关闭OSSClient。
        ossClient.shutdown();

        return newImgName;
    }

    //上传文件流
    public static String InPutUpload(MultipartFile imgFile) throws IOException {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        String originalFilename = imgFile.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newImgName = UUID.randomUUID() + substring;

        // 创建PutObjectRequest对象。
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newImgName, imgFile.getInputStream());

        // 上传文件。
        ossClient.putObject(putObjectRequest);
        // 关闭OSSClient。
        ossClient.shutdown();

        return newImgName;
    }

    //删除单个文件
    public static void deleteFile(String objectName){
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(bucketName, objectName);
        // 关闭OSSClient。
        ossClient.shutdown();
    }
}
